//
//  AVCaptureViewController.m
//  CaptureDemo
//
//  Created by 苏沫离 on 2018/9/11.
//  Copyright © 2018年 苏沫离. All rights reserved.
//

#import "AVCaptureViewController.h"
#import "AVCapturePreviewView.h"
#import "AVImageViewController.h"
#import "AVCamPhotoCaptureDelegate.h"
#import <AVFoundation/AVFoundation.h>

API_AVAILABLE(ios(10.2))
@interface AVCaptureViewController ()
<AVCapturePreviewViewDelegate>

@property (nonatomic ,strong) UIButton *recordButton;//拍照按钮
@property (nonatomic ,strong) UIButton *livePhotoButton;//动态照片
@property (nonatomic ,strong) UIButton *devicePositionButton;//镜头位置
@property (nonatomic ,strong) UIButton *flashModelButton;//闪光灯

@property (nonatomic ,strong) UILabel *livePhotoLogoLable;//livePhoto Logo


@property (nonatomic ,strong) dispatch_queue_t sessionQueue;//配置AVCaptureSession的串行队列
@property (nonatomic ,strong) AVCaptureDeviceInput *videoDeviceInput;//数据源输入
@property (nonatomic ,strong) AVCaptureDevice *device;//硬件管理
@property (nonatomic ,strong) AVCaptureSession *session;//会话管理
@property (nonatomic ,strong) AVCapturePhotoOutput *photoOutput;//输出管理
@property (nonatomic, strong) AVCapturePreviewView *previewView;//预览界面


@property (nonatomic) NSInteger inProgressLivePhotoCapturesCount;
@property (nonatomic) NSMutableDictionary<NSNumber *, AVCamPhotoCaptureDelegate *> *inProgressPhotoCaptureDelegates;


@end

@implementation AVCaptureViewController

#pragma mark - life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    /****   界面元素设置    ****/
    [self.view addSubview:self.previewView];
    [self.view addSubview:self.recordButton];
    [self.view addSubview:self.flashModelButton];
    [self.view addSubview:self.devicePositionButton];
    [self.view addSubview:self.livePhotoButton];
    [self.view addSubview:self.livePhotoLogoLable];
    self.devicePositionButton.frame = CGRectMake(CGRectGetWidth(UIScreen.mainScreen.bounds) - (38 + 26 + 18), 0, 38 + 26 + 18, 26 + 24 + 10);
    self.flashModelButton.frame = CGRectMake(self.devicePositionButton.frame.origin.x - (18 + 20 + 18), 0, 18 + 20 + 18, 26 + 24 + 10);
    self.livePhotoButton.frame = CGRectMake(self.flashModelButton.frame.origin.x - 80, 0, 80, 60);
    self.livePhotoLogoLable.frame = CGRectMake(80, 20, 60, 20);
    
    self.sessionQueue = dispatch_queue_create("com.CaptureDemo.sessionQueue", DISPATCH_QUEUE_SERIAL);
    [self getAuthorizationStatus];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    
    dispatch_async(self.sessionQueue, ^{
        [self.session startRunning];
    } );
}

- (void)viewDidDisappear:(BOOL)animated
{
    dispatch_async( self.sessionQueue, ^{
        [self.session stopRunning];
    });
    
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - response click

- (void)recordButtonClick:(UIButton *)sender
{
    AVCaptureVideoOrientation videoPreviewLayerVideoOrientation = self.previewView.videoPreviewLayer.connection.videoOrientation;
    dispatch_async(self.sessionQueue, ^{
       
        //更新照片输出的连接以匹配视频预览层的视频方向。
        AVCaptureConnection *photoOutputConnection = [self.photoOutput connectionWithMediaType:AVMediaTypeVideo];
        photoOutputConnection.videoOrientation = videoPreviewLayerVideoOrientation;

        //支持捕获HEIF照片时，与闪光设置为自动和高分辨率照片启用。
        AVCapturePhotoSettings *photoSettings;
        if (@available(iOS 11.0, *)) {
            if ( [self.photoOutput.availablePhotoCodecTypes containsObject:AVVideoCodecTypeHEVC] ) {
                photoSettings = [AVCapturePhotoSettings photoSettingsWithFormat:@{ AVVideoCodecKey : AVVideoCodecTypeHEVC }];
            }
            else {
                photoSettings = [AVCapturePhotoSettings photoSettings];
            }
        } else {
            photoSettings = [AVCapturePhotoSettings photoSettings];
        }
        
        if (self.videoDeviceInput.device.isFlashAvailable) {
            photoSettings.flashMode = AVCaptureFlashModeAuto;
        }
        
        photoSettings.highResolutionPhotoEnabled = YES;
        if ( photoSettings.availablePreviewPhotoPixelFormatTypes.count > 0 ) {
            photoSettings.previewPhotoFormat = @{(NSString *)kCVPixelBufferPixelFormatTypeKey : photoSettings.availablePreviewPhotoPixelFormatTypes.firstObject};
        }
        
        //在电影模式下不支持动态照片
        if ( self.livePhotoButton.selected && self.photoOutput.livePhotoCaptureSupported ) {
            NSString *livePhotoMovieFileName = [NSUUID UUID].UUIDString;
            NSString *livePhotoMovieFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[livePhotoMovieFileName stringByAppendingPathExtension:@"mov"]];
            photoSettings.livePhotoMovieFileURL = [NSURL fileURLWithPath:livePhotoMovieFilePath];
        }

        if (@available(iOS 11.0, *)) {
            photoSettings.depthDataDeliveryEnabled = NO;
        }
        
        
        AVCamPhotoCaptureDelegate *photoCaptureDelegate = [[AVCamPhotoCaptureDelegate alloc] initWithRequestedPhotoSettings:photoSettings willCapturePhotoAnimation:^{
            
            //即将拍摄照片的回调
            dispatch_async( dispatch_get_main_queue(), ^{
                self.previewView.videoPreviewLayer.opacity = 0.0;
                [UIView animateWithDuration:0.25 animations:^{
                    self.previewView.videoPreviewLayer.opacity = 1.0;
                }];
            } );
            
        } livePhotoCaptureHandler:^(BOOL capturing) {
            
            /*
             由于实时照片捕获可能会重叠，
             因此我们需要跟踪正在进行的实时照片捕获的数量，
             以确保在这些捕获过程中实时照片标签保持可见。
             */
            if ( capturing ) {
                self.inProgressLivePhotoCapturesCount++;
            }
            else {
                self.inProgressLivePhotoCapturesCount--;
            }

            NSInteger inProgressLivePhotoCapturesCount = self.inProgressLivePhotoCapturesCount;
            dispatch_async( dispatch_get_main_queue(), ^{
                if ( inProgressLivePhotoCapturesCount > 0 ) {
                    self.livePhotoLogoLable.hidden = NO;
                }
                else if ( inProgressLivePhotoCapturesCount == 0 ) {
                    self.livePhotoLogoLable.hidden = YES;
                }
                else {
                    NSLog( @"Error: In progress live photo capture count is less than 0" );
                }
            } );
            
            
            
        } completionHandler:^(AVCamPhotoCaptureDelegate *photoCaptureDelegate) {
            
            //捕获完成后，删除对照片捕获委托的引用，以便可以取消分配。
            dispatch_async( self.sessionQueue, ^{
                self.inProgressPhotoCaptureDelegates[@(photoCaptureDelegate.requestedPhotoSettings.uniqueID)] = nil;
            } );
        }];
        
        //Photo Output保留对照片捕获委托的弱引用，因此我们将其存储在数组中以保持对此对象的强引用，直到捕获完成为止。
        self.inProgressPhotoCaptureDelegates[@(photoCaptureDelegate.requestedPhotoSettings.uniqueID)] = photoCaptureDelegate;
        [self.photoOutput capturePhotoWithSettings:photoSettings delegate:photoCaptureDelegate];
    });
}

- (void)focusAndExposeTapLocation:(CGPoint)tapPoint
{
    dispatch_async( self.sessionQueue, ^{
        AVCaptureDevice *device = self.videoDeviceInput.device;
        NSError *error = nil;
        if ([device lockForConfiguration:&error] ) {
            
            /*
             设置(焦点/曝光)点不会启动(焦点/曝光)操作。
             调用set(焦点/曝光)模式()来应用新的感兴趣点。
             */
            if ( device.isFocusPointOfInterestSupported && [device isFocusModeSupported:AVCaptureFocusModeAutoFocus] ) {
                device.focusPointOfInterest = tapPoint;
                device.focusMode = AVCaptureFocusModeAutoFocus;
            }
            
            if ( device.isExposurePointOfInterestSupported && [device isExposureModeSupported:AVCaptureExposureModeAutoExpose] ) {
                device.exposurePointOfInterest = tapPoint;
                device.exposureMode = AVCaptureExposureModeAutoExpose;
            }
            
            device.subjectAreaChangeMonitoringEnabled = YES;
            [device unlockForConfiguration];
        }
        else {
            NSLog( @"Could not lock device for configuration: %@", error );
        }
    } );
}

//切换镜头位置
- (void)switchCameraLocationButtonClick
{
    self.recordButton.enabled = NO;
    self.devicePositionButton.enabled = NO;
    self.flashModelButton.enabled = NO;
    
    dispatch_async(self.sessionQueue, ^{
        
        if (@available(iOS 10.2, *)){
            
            AVCaptureDevice *currentVideoDevice = self.videoDeviceInput.device;
            AVCaptureDevicePosition currentPosition = currentVideoDevice.position;
            AVCaptureDevicePosition preferredPosition;
            AVCaptureDeviceType preferredDeviceType;
            
            switch (currentPosition)
            {
                case AVCaptureDevicePositionUnspecified:
                case AVCaptureDevicePositionFront:
                    preferredPosition = AVCaptureDevicePositionBack;
                    preferredDeviceType = AVCaptureDeviceTypeBuiltInDualCamera;
                    break;
                case AVCaptureDevicePositionBack:
                    preferredPosition = AVCaptureDevicePositionFront;
                    preferredDeviceType = AVCaptureDeviceTypeBuiltInWideAngleCamera;
                    break;
            }

            NSArray<AVCaptureDeviceType> *deviceTypes = @[AVCaptureDeviceTypeBuiltInWideAngleCamera, AVCaptureDeviceTypeBuiltInDualCamera];
            AVCaptureDeviceDiscoverySession *sessionDiscovery = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:deviceTypes mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionUnspecified];
            
            NSArray<AVCaptureDevice *> *devices = sessionDiscovery.devices;
            __block AVCaptureDevice *newVideoDevice = nil;
            [devices enumerateObjectsUsingBlock:^(AVCaptureDevice * _Nonnull device, NSUInteger idx, BOOL * _Nonnull stop) {
                if ( device.position == preferredPosition && [device.deviceType isEqualToString:preferredDeviceType] ) {
                    newVideoDevice = device;
                    * stop = YES;
                }
            }];
            
            if ( !newVideoDevice)
            {
                [devices enumerateObjectsUsingBlock:^(AVCaptureDevice * _Nonnull device, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ( device.position == preferredPosition) {
                        newVideoDevice = device;
                        * stop = YES;
                    }
                }];
            }
            
            if ( newVideoDevice )
            {
                AVCaptureDeviceInput *videoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:newVideoDevice error:NULL];
                
                [self.session beginConfiguration];
                
                //删除现有设备输入，因为不支持同时使用前后摄像头。
                [self.session removeInput:self.videoDeviceInput];
                
                if ( [self.session canAddInput:videoDeviceInput] ) {
                    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceSubjectAreaDidChangeNotification object:currentVideoDevice];
                    
                    [self.session addInput:videoDeviceInput];
                    self.videoDeviceInput = videoDeviceInput;
                }
                else {
                    [self.session addInput:self.videoDeviceInput];
                }
                
                AVCaptureConnection *movieFileOutputConnection = [self.photoOutput connectionWithMediaType:AVMediaTypeVideo];
                if ( movieFileOutputConnection.isVideoStabilizationSupported ) {
                    movieFileOutputConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
                }
                
                //是否开启动态照片
                self.photoOutput.livePhotoCaptureEnabled = self.livePhotoButton.selected;
                //self.photoOutput.depthDataDeliveryEnabled = NO;

                [self.session commitConfiguration];
            }
            
        }

        
        
        dispatch_async( dispatch_get_main_queue(), ^{
            self.devicePositionButton.enabled = YES;
            self.flashModelButton.enabled = YES;
            self.recordButton.enabled = YES;
        } );
    });
    
}

//闪光灯模式：开 --> 关 --> 自动
- (void)flashModelButtonClick:(UIButton *)sender
{
    dispatch_async( self.sessionQueue, ^{
        AVCaptureDevice *device = self.videoDeviceInput.device;
        
        //是否有闪光灯，闪光灯当前是否可用：如果设备过热并需要冷却，闪光灯可能会变得不可用
        if (device.hasFlash == NO || device.flashAvailable == NO) {
            return ;
        }
        
        NSError *error = nil;
        if ([device lockForConfiguration:&error] ) {
            
            switch (device.flashMode){
                case AVCaptureFlashModeAuto:{
                    if ([device isFlashModeSupported:AVCaptureFlashModeOn]){
                        [device setFlashMode:AVCaptureFlashModeOn];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [sender setImage:resourceImage(@"cameraFlash_On") forState:UIControlStateNormal];
                        });
                    }
                }
                    break;
                case AVCaptureFlashModeOff:{
                    if ([device isFlashModeSupported:AVCaptureFlashModeAuto]){
                        [device setFlashMode:AVCaptureFlashModeAuto];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [sender setImage:resourceImage(@"cameraFlash_Auto") forState:UIControlStateNormal];
                        });
                    }

                }
                    break;
                case AVCaptureFlashModeOn: {
                    if ([device isFlashModeSupported:AVCaptureFlashModeOff]){
                        [device setFlashMode:AVCaptureFlashModeOff];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [sender setImage:resourceImage(@"cameraFlash_Off") forState:UIControlStateNormal];
                        });
                    }
                }
                    break;
                default:
                    break;
            }
            
            [device unlockForConfiguration];
        }
        else {
            NSLog( @"Could not lock device for configuration: %@", error );
        }
    });
}

- (void)livePhotoButtonClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
}

#pragma mark - private method

- (void)getAuthorizationStatus
{
    switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo])
    {
        case AVAuthorizationStatusNotDetermined:
        {
            dispatch_suspend(self.sessionQueue);

            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted)
             {
                 if (granted){
                     dispatch_resume(self.sessionQueue);
                     dispatch_async(dispatch_get_main_queue(), ^{
                         [self configurationCaptureMethod];
                     });
                 }
                 NSLog(@"granted --- %d currentThread : %@",granted,NSThread.currentThread);
             }];
            NSLog(@"用户尚未授予或拒绝该权限:AVAuthorizationStatusNotDetermined");
        }
            break;
        case AVAuthorizationStatusRestricted:
            NSLog(@"不允许用户访问媒体捕获设备:AVAuthorizationStatusRestricted");
            break;
        case AVAuthorizationStatusDenied:
            NSLog(@"用户已经明确拒绝了应用访问捕获设备:AVAuthorizationStatusDenied");
            break;
        case AVAuthorizationStatusAuthorized:
            [self configurationCaptureMethod];
            NSLog(@"用户授予应用访问捕获设备的权限:AVAuthorizationStatusAuthorized");
            break;
        default:
            break;
    }
}

- (void)configurationCaptureMethod
{
    self.session = [[AVCaptureSession alloc] init];
    self.previewView.session = self.session;
    
    dispatch_async( self.sessionQueue, ^{
        
        [self.session beginConfiguration];

        AVCaptureDevice *videoDevice;
        if (@available(iOS 10.2, *))
        {
            videoDevice = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltInDualCamera mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionBack];
            if ( !videoDevice )
            {
                videoDevice = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltInWideAngleCamera mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionBack];
                
                if ( !videoDevice )
                {
                    videoDevice = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltInWideAngleCamera mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionFront];
                }
            }
        }
        else
        {
            //返回的总是AVCaptureDeviceTypeBuiltInWideAngleCamera设备类型
            videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        }

        NSError *error = nil;
        
        AVCaptureDeviceInput *videoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
        if (!videoDeviceInput)
        {
            [self.session commitConfiguration];
            return;
        }
        
        
        if ( [self.session canAddInput:videoDeviceInput] )
        {
            [self.session addInput:videoDeviceInput];
            self.videoDeviceInput = videoDeviceInput;
            
            dispatch_async( dispatch_get_main_queue(), ^{

                //使用状态栏方向作为初始视频方向
                UIInterfaceOrientation statusBarOrientation = [UIApplication sharedApplication].statusBarOrientation;
                AVCaptureVideoOrientation initialVideoOrientation = AVCaptureVideoOrientationPortrait;
                if ( statusBarOrientation != UIInterfaceOrientationUnknown ) {
                    initialVideoOrientation = (AVCaptureVideoOrientation)statusBarOrientation;
                }
                
                self.previewView.videoPreviewLayer.connection.videoOrientation = initialVideoOrientation;
            } );
        }
        else
        {
            [self.session commitConfiguration];
            return;
        }
        
        
        //添加输出
        AVCapturePhotoOutput *photoOutput = [[AVCapturePhotoOutput alloc] init];
        if ([self.session canAddOutput:photoOutput]){
            [self.session addOutput:photoOutput];
            self.photoOutput = photoOutput;
            
            self.photoOutput.highResolutionCaptureEnabled = YES;
            self.photoOutput.livePhotoCaptureEnabled = self.livePhotoButton.selected;
            
            self.inProgressPhotoCaptureDelegates = [NSMutableDictionary dictionary];
            self.inProgressLivePhotoCapturesCount = 0;

        }
        else
        {
            [self.session commitConfiguration];
            return;
        }
        
        [self.session commitConfiguration];
    });
}


- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    
    if ( UIDeviceOrientationIsPortrait( deviceOrientation ) || UIDeviceOrientationIsLandscape( deviceOrientation ) ) {
        self.previewView.videoPreviewLayer.connection.videoOrientation = (AVCaptureVideoOrientation)deviceOrientation;
    }
}

#pragma mark - setter and getter

- (AVCapturePreviewView *)previewView
{
    if (_previewView == nil)
    {
        _previewView = [[AVCapturePreviewView alloc] initWithFrame:UIScreen.mainScreen.bounds];
        _previewView.delegate = self;
    }
    return _previewView;
}

- (UILabel *)livePhotoLogoLable
{
    if (_livePhotoLogoLable == nil) {
        _livePhotoLogoLable = [[UILabel alloc] init];
        _livePhotoLogoLable.text = @"live";
        _livePhotoLogoLable.textAlignment = NSTextAlignmentCenter;
        _livePhotoLogoLable.backgroundColor = [UIColor yellowColor];
        _livePhotoLogoLable.textColor = [UIColor blueColor];
        _livePhotoLogoLable.hidden = YES;
    }
    return _livePhotoLogoLable;
}

- (UIButton *)flashModelButton
{
    if (_flashModelButton == nil)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.adjustsImageWhenHighlighted = NO;
        button.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
        [button setImage:resourceImage(@"cameraFlash_Auto") forState:UIControlStateNormal];
        button.imageEdgeInsets = UIEdgeInsetsMake(26, 18, 10, 18);
        [button addTarget:self action:@selector(flashModelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        _flashModelButton = button;
    }
    return _flashModelButton;
}

- (UIButton *)devicePositionButton
{
    if (_devicePositionButton == nil)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:resourceImage(@"fanzhuan") forState:UIControlStateNormal];
        button.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        button.imageEdgeInsets = UIEdgeInsetsMake(26, 0, 0, 38);
        [button addTarget:self action:@selector(switchCameraLocationButtonClick) forControlEvents:UIControlEventTouchUpInside];
        _devicePositionButton = button;
    }
    return _devicePositionButton;
}

- (UIButton *)livePhotoButton
{
    if (_livePhotoButton == nil)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.titleLabel.font = [UIFont systemFontOfSize:13];
        [button setTitle:@"Live On" forState:UIControlStateNormal];
        [button setTitle:@"Live Off" forState:UIControlStateSelected];
        button.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        button.titleEdgeInsets = UIEdgeInsetsMake(30, 0, 0, 0);
        [button addTarget:self action:@selector(livePhotoButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        _livePhotoButton = button;
    }
    return _livePhotoButton;
}

- (UIButton *)recordButton
{
    if (_recordButton == nil)
    {
        _recordButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _recordButton.frame = CGRectMake(CGRectGetWidth(UIScreen.mainScreen.bounds) * 1/2.0 - 30,CGRectGetHeight(UIScreen.mainScreen.bounds) - 32 - 60, 60, 60);
        _recordButton.layer.backgroundColor = [UIColor.whiteColor colorWithAlphaComponent:0.7f].CGColor;;
        CAShapeLayer *backmMaskLayer = [CAShapeLayer layer];
        backmMaskLayer.frame = _recordButton.layer.bounds;
        backmMaskLayer.path = [UIBezierPath bezierPathWithRoundedRect:_recordButton.layer.bounds cornerRadius:(CGRectGetWidth(_recordButton.layer.frame) / 2.0)].CGPath;
        _recordButton.layer.mask = backmMaskLayer;
        
        
        CALayer *contentLayer = [CALayer layer];
        contentLayer.backgroundColor = UIColor.whiteColor.CGColor;
        contentLayer.frame = CGRectMake(4, 4, CGRectGetWidth(_recordButton.frame) - 8,  CGRectGetHeight(_recordButton.frame) - 8);
        CAShapeLayer *contentMaskLayer = [CAShapeLayer layer];
        contentMaskLayer.frame = contentLayer.bounds;
        contentMaskLayer.path = [UIBezierPath bezierPathWithRoundedRect:contentLayer.bounds cornerRadius:(CGRectGetWidth(contentLayer.frame) / 2.0)].CGPath;
        contentLayer.mask = contentMaskLayer;
        
        [_recordButton.layer addSublayer:contentLayer];
        
        [_recordButton addTarget:self action:@selector(recordButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _recordButton;
}

@end
